package org.huawei.controller;

import javafx.stage.Stage;
import org.huawei.dao.HomeworkDao;
import org.huawei.model.domain.Homework;
import org.huawei.model.domain.HomeworkStudent;
import org.huawei.model.domain.User;
import org.huawei.utils.DatabaseUtil;
import org.huawei.annotations.RateLimit;
import org.huawei.view.AlartView;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

public class HomeworkController {
    private Stage stage;
    private HomeworkDao homeworkDao;

    public HomeworkController(Stage stage) {
        this.stage = stage;
        this.homeworkDao = new HomeworkDao();
    }

    @RateLimit
    public List<Homework> tryGetHomeworkByUser(User currentUser, boolean hasPermissionToGetAll) throws SQLException {
        if(hasPermissionToGetAll){
            return homeworkDao.getHomeworksByUserId(currentUser);
        }else{
            return homeworkDao.getAllHomeworks();
        }
    }

    @RateLimit
    public void addHomework(Homework homework) throws SQLException {
        homework.setSubmissionTimes(0);
        LocalDate endDate = homework.getHomeworkEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        if (endDate.isBefore(LocalDate.now())) {
            homework.setHomeworkStatus(Homework.HomeworkStatus.OVERDUE);
        } else {
            homework.setHomeworkStatus(Homework.HomeworkStatus.ASSIGNED);
        }
        homework.setHomeworkGrade(0);

        homeworkDao.addHomework(homework);
    }

    @RateLimit
    public void updateHomeworkInDatabase(Homework homework) throws SQLException {
        // 如果更新终止日期，需要判断作业的状态
        if (!homework.getHomeworkStatus().equals(Homework.HomeworkStatus.DELETED)) {
            Date endDate = homework.getHomeworkEndDate();
            Date currentDate = new Date();

            if (endDate.before(currentDate)) {
                homework.setHomeworkStatus(Homework.HomeworkStatus.OVERDUE);
            } else {
                homework.setHomeworkStatus(Homework.HomeworkStatus.ASSIGNED);
            }
        }
        try {
            homeworkDao.updateHomework(homework);
        } catch (SQLException e) {
            e.printStackTrace();
            AlartView.alart(stage, "错误！");
        }
    }

    @RateLimit
    public void updateHomeworkDataOnLogin() throws SQLException {
        List<Integer> homeworkIds = homeworkDao.getAllHomeworkIds();

        for (int homeworkId : homeworkIds) {
            homeworkDao.updateAverageGrade(homeworkId);
            homeworkDao.updateSubmissionTimes(homeworkId);
            homeworkDao.updateHomeworkStatus(homeworkId);
        }
    }

    @RateLimit
    public void addHomeworkStudent(HomeworkStudent homeworkStudent) throws SQLException {
        String query = "INSERT INTO homework_student (HomeworkId, StudentId, Status) VALUES (?, ?, ?)";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            stmt.setInt(1, homeworkStudent.getHomeworkId());
            stmt.setInt(2, homeworkStudent.getStudentId());
            stmt.setString(3, homeworkStudent.getStatus().name());

            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new SQLException("Error inserting homework-student relation for HomeworkId: "
                    + homeworkStudent.getHomeworkId() + ", StudentId: " + homeworkStudent.getStudentId(), e);
        }
    }

    @RateLimit
    public List<Homework> fetchHomeworksForStudent(int studentId) {
        return homeworkDao.fetchHomeworksForStudent(studentId);
    }
}
